package com.chongyahhh.security.security.configs.wechat;

import com.chongyahhh.security.security.common.CommonAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.stereotype.Component;

/**
 * @Author chongyahhh
 * 微信登录配置
 */
@Component
public class WechatLoginConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final WechatAuthenticationProvider wechatAuthenticationProvider;

    private final String WECHAT_LOGIN_URL = "/user/wechatLogin";

    @Autowired
    public WechatLoginConfig(WechatAuthenticationProvider wechatAuthenticationProvider) {
        this.wechatAuthenticationProvider = wechatAuthenticationProvider;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        CommonAuthenticationFilter commonAuthenticationFilter = new CommonAuthenticationFilter(WECHAT_LOGIN_URL, new WechatAuthenticationProcessor());
        // 使自定义的 Filter 可以获取到 ProviderManager
        commonAuthenticationFilter.setAuthenticationManager(http.getSharedObject((AuthenticationManager.class)));

        http
                .authenticationProvider(wechatAuthenticationProvider)
                // 注意自定义 Filter 插入的位置
                .addFilterAfter(commonAuthenticationFilter, ExceptionTranslationFilter.class);
    }
}
